import React, { useEffect, useRef, useState } from 'react';
import { Chart } from '@antv/g2';
import { Card, Select, DatePicker, Space, Spin, InputNumber, Switch, Button, Tooltip, message } from 'antd';
import { LineChartOutlined, SettingOutlined, ReloadOutlined, FullscreenOutlined } from '@ant-design/icons';
import './ErrorTrendChart.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface TrendDataPoint {
  time: string;
  errorCount: number;
  errorRate: number;
  severity: 'low' | 'medium' | 'high' | 'critical';
  type: string;
  details?: any[];
}

interface ErrorTrendChartProps {
  data: TrendDataPoint[];
  loading?: boolean;
  height?: number;
  onTimeRangeChange?: (range: string) => void;
  onMetricChange?: (metric: string) => void;
  onDataPointClick?: (data: TrendDataPoint) => void;
  realTimeEnabled?: boolean;
  onRealTimeToggle?: (enabled: boolean) => void;
}

const ErrorTrendChart: React.FC<ErrorTrendChartProps> = ({
  data,
  loading = false,
  height = 400,
  onTimeRangeChange,
  onMetricChange,
  onDataPointClick,
  realTimeEnabled = false,
  onRealTimeToggle
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<Chart | null>(null);
  const [timeRange, setTimeRange] = useState('24h');
  const [metric, setMetric] = useState('errorCount');
  const [granularity, setGranularity] = useState('hour');
  const [threshold, setThreshold] = useState(100);
  const [showThreshold, setShowThreshold] = useState(true);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 时间粒度选项
  const granularityOptions: Record<string, Array<{value: string, label: string}>> = {
    '1h': [{ value: 'minute', label: '分钟级' }],
    '24h': [{ value: 'minute', label: '分钟级' }, { value: 'hour', label: '小时级' }],
    '7d': [{ value: 'hour', label: '小时级' }, { value: 'day', label: '天级' }],
    '30d': [{ value: 'day', label: '天级' }]
  };

  // 获取严重程度颜色
  const getSeverityColor = (severity: string) => {
    const colors: Record<string, string> = {
      low: '#52c41a',
      medium: '#faad14', 
      high: '#ff7a45',
      critical: '#ff4d4f'
    };
    return colors[severity] || '#1890ff';
  };

  // 处理时间范围变化
  const handleTimeRangeChange = (range: string) => {
    setTimeRange(range);
    // 根据时间范围自动调整粒度
    const defaultGranularity: Record<string, string> = {
      '1h': 'minute',
      '24h': 'hour', 
      '7d': 'hour',
      '30d': 'day'
    };
    setGranularity(defaultGranularity[range] || 'hour');
    onTimeRangeChange?.(range);
  };

  // 处理指标变化
  const handleMetricChange = (newMetric: string) => {
    setMetric(newMetric);
    onMetricChange?.(newMetric);
  };

  // 处理实时更新切换
  const handleRealTimeToggle = (enabled: boolean) => {
    onRealTimeToggle?.(enabled);
    if (enabled) {
      message.success('已开启实时更新');
    } else {
      message.info('已关闭实时更新');
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    onTimeRangeChange?.(timeRange);
    message.success('数据已刷新');
  };

  useEffect(() => {
    // 添加更安全的条件检查
    if (!chartRef.current || loading || !data || !Array.isArray(data) || data.length === 0) {
      return;
    }
  
    // 销毁之前的图表实例
    if (chartInstance.current) {
      chartInstance.current.destroy();
      chartInstance.current = null;
    }
  
    // 处理数据，确保severity字段存在
    const processedData = data.map(item => ({
      ...item,
      time: new Date(item.time).getTime(),
      value: metric === 'errorCount' ? item.errorCount : item.errorRate,
      // 如果后端没有提供severity，则根据错误数量计算
      severity: item.severity || (
        item.errorCount >= 50 ? 'critical' : 
        item.errorCount >= 20 ? 'high' : 
        item.errorCount >= 5 ? 'medium' : 'low'
      )
    }));
  
    // 创建新的图表实例
    const chart = new Chart({
      container: chartRef.current,
      autoFit: true,
      height: isFullscreen ? window.innerHeight - 200 : height,
    });
  
    // 设置数据
    chart.data(processedData);
  
    // 添加阈值线（如果需要）
    if (showThreshold && metric === 'errorCount') {
      const thresholdData = [{ value: threshold }];
      chart
        .lineY()
        .data(thresholdData)
        .encode('y', 'value')
        .style({
          stroke: '#ff4d4f',
          strokeWidth: 2,
          strokeDasharray: [4, 4]
        });
    }
  
    // 绘制柱状图（替换原来的面积图和折线图）
    chart
      .interval()
      .encode('x', 'time')
      .encode('y', 'value')
      .encode('color', 'severity')
      .scale('color', {
        range: ['#52c41a', '#faad14', '#ff7a45', '#ff4d4f']
      })
      .style({
        radius: 4, // 圆角
        cursor: 'pointer'
      })
      .tooltip({
        title: (d) => new Date(d.time).toLocaleString(),
        items: [
          {
            name: metric === 'errorCount' ? '错误数量' : '错误率',
            value: (d) => d.value + (metric === 'errorCount' ? ' 个' : '%')
          }
        ]
      });
  
    // 设置坐标轴
    chart.scale('time', {
      type: 'time',
      tickCount: 8,
      nice: true
    });
    
    chart.scale('value', {
      nice: true,
      min: 0
    });
  
    // 添加交互
    chart.interaction('tooltip', {
      shared: false,
      crosshairs: {
        x: true,
        y: false
      }
    });
  
    // 添加点击事件
    chart.on('interval:click', (event: any) => {
      const data = event.data?.data;
      if (data && onDataPointClick) {
        onDataPointClick(data);
      }
    });
  
    chart.render();
    chartInstance.current = chart;
  
    // 清理函数
    return () => {
      if (chartInstance.current) {
        chartInstance.current.destroy();
        chartInstance.current = null;
      }
    };
  }, [data, loading, metric, granularity, threshold, showThreshold, height, isFullscreen]);

  return (
    <Card 
      className={`error-trend-chart ${isFullscreen ? 'fullscreen' : ''}`}
      title={
        <Space>
          <LineChartOutlined />
          <span>错误趋势分析</span>
          {realTimeEnabled && <span className="realtime-indicator">🔴 实时</span>}
        </Space>
      }
      extra={
        <Space>
          <Tooltip title="全屏显示">
            <Button 
              type="text" 
              icon={<FullscreenOutlined />} 
              onClick={() => setIsFullscreen(!isFullscreen)}
            />
          </Tooltip>
          <Tooltip title="刷新数据">
            <Button type="text" icon={<ReloadOutlined />} onClick={handleRefresh} />
          </Tooltip>
        </Space>
      }
    >
      {/* 控制面板 */}
      <div className="chart-controls">
        <Space wrap>
          <div className="control-group">
            <label>时间范围:</label>
            <Select
              value={timeRange}
              onChange={handleTimeRangeChange}
              style={{ width: 120 }}
            >
              <Option value="1h">最近1小时</Option>
              <Option value="24h">最近24小时</Option>
              <Option value="7d">最近7天</Option>
              <Option value="30d">最近30天</Option>
            </Select>
          </div>

          <div className="control-group">
            <label>时间粒度:</label>
            <Select
              value={granularity}
              onChange={setGranularity}
              style={{ width: 100 }}
            >
              {granularityOptions[timeRange]?.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </div>

          <div className="control-group">
            <label>指标:</label>
            <Select
              value={metric}
              onChange={handleMetricChange}
              style={{ width: 100 }}
            >
              <Option value="errorCount">错误数量</Option>
              <Option value="errorRate">错误率</Option>
            </Select>
          </div>

          {metric === 'errorCount' && (
            <div className="control-group">
              <label>警戒线:</label>
              <InputNumber
                value={threshold}
                onChange={(value) => setThreshold(value || 0)}
                min={0}
                style={{ width: 80 }}
                disabled={!showThreshold}
              />
              <Switch
                checked={showThreshold}
                onChange={setShowThreshold}
                size="small"
                style={{ marginLeft: 8 }}
              />
            </div>
          )}

          <div className="control-group">
            <label>实时更新:</label>
            <Switch
              checked={realTimeEnabled}
              onChange={handleRealTimeToggle}
              checkedChildren="开"
              unCheckedChildren="关"
            />
          </div>
        </Space>
      </div>

      {/* 图表容器 */}
      <div className="chart-container">
        {loading ? (
          <div className="chart-loading">
            <Spin size="large" tip="加载中..." />
          </div>
        ) : (
          <div ref={chartRef} className="chart-content" />
        )}
      </div>

      {/* 图例说明 */}
      <div className="chart-legend">
        <Space>
          <span className="legend-item">
            <span className="legend-color" style={{ backgroundColor: '#52c41a' }}></span>
            低风险
          </span>
          <span className="legend-item">
            <span className="legend-color" style={{ backgroundColor: '#faad14' }}></span>
            中风险
          </span>
          <span className="legend-item">
            <span className="legend-color" style={{ backgroundColor: '#ff7a45' }}></span>
            高风险
          </span>
          <span className="legend-item">
            <span className="legend-color" style={{ backgroundColor: '#ff4d4f' }}></span>
            严重
          </span>
        </Space>
      </div>
    </Card>
  );
};

export default ErrorTrendChart;